package cn.itrip.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.beans.vo.userinfo.ItripUserVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import cn.itrip.service.TokenService;
import cn.itrip.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;

/**
 * @author jie
 * @date 2019/5/7 -10:10
 */
@Controller
public class UserController {

    @Resource
    private RedisAPI redisAPI;

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    @ApiOperation(value = "登录",httpMethod = "post",produces = "application/json")
    @ResponseBody
    @RequestMapping(value ="login",method = RequestMethod.POST)
    public Dto login(@RequestParam String username, @RequestParam String pwd , HttpServletRequest request) throws Exception{
        ItripUser user = userService.login(username, MD5.getMd5(pwd,32));
        if (user!=null){
            String token = tokenService.genernateToken(request.getHeader("user-agent"), user);
            tokenService.saveToken(token,user);
            ItripTokenVO tokenVO = new ItripTokenVO(token,
                    Calendar.getInstance().getTimeInMillis()+2*60*60*1000,
                    Calendar.getInstance().getTimeInMillis());
            return DtoUtil.returnSuccess("登录成功",tokenVO);
        }else{
            return DtoUtil.returnFail("用户名或密码错误","245");
        }
    }

    @ApiOperation(value = "注册",produces ="application/json",httpMethod = "post")
    @RequestMapping(value = "register",method = RequestMethod.POST)
    @ResponseBody
    public Dto register(@RequestBody ItripUserVO itripUserVO) throws Exception{
        ItripUser user = new ItripUser();
        user.setUserCode(itripUserVO.getUserCode());
        user.setUserPassword(itripUserVO.getUserPassword());
        user.setCreationDate(new Date());
        user.setUserType(0);
        user.setActivated(1);
        user.setUserName(itripUserVO.getUserName());
        Integer integer = userService.addUser(user);
        if (integer>0){
            return DtoUtil.returnSuccess("注册成功");
        }else {
            return DtoUtil.returnSuccess("注册失败");
        }
    }

    @ApiOperation(value = "logout",produces = "application/json",httpMethod = "post")
    @ResponseBody
    @RequestMapping(value = "logout",method = RequestMethod.POST)
    public Dto logout(@RequestParam String token) throws  Exception{
        if (redisAPI.get(token)!=null){
            tokenService.delToken(token);
            return  DtoUtil.returnSuccess("注销成功");
        }else {
            return  DtoUtil.returnSuccess("token不存在");
        }
    }
}
